package com.google.code.gaestats;

import com.google.appengine.api.memcache.Expiration;
import static com.google.code.gaestats.StatsObjectifyFactory.ms;
import com.googlecode.objectify.annotation.EntitySubclass;

/**
 *
 * @author JaggardM
 */
@EntitySubclass
public class ValuedCounter extends Counter
{

	protected static final String V_PREFIX = "V_";

	private ValuedCounter()
	{
	}

	protected ValuedCounter(String name)
	{
		super(V_PREFIX + name);
	}

	public long value(Long value)
	{
		long id = ms().increment(getName() + COUNTER, 1L, 1L);
		TimedValue timedValue = new TimedValue(value);
		ms().put(getName() + NUMBER_SEPERATOR + id, timedValue, Expiration.byDeltaSeconds(GAEStats.SECONDS_BETWEEN_PERSISTANCE));
		return id;
	}

	@Override
	protected void updateCounterData(PerMinuteCounterData pmcd, PerHourCounterData phcd, Iterable<Object> data)
	{
		//Data should be a collection of TimedValue<Long> objects.
		for (Object datum : data)
		{
			if (datum != null && datum instanceof TimedValue)
			{
				TimedValue tv = (TimedValue) datum;
				Long curr = tv.getValue();
				Statistics toAdd = new Statistics(curr, curr, 1L, curr);
				pmcd.writeStatistics(tv.getTime(), toAdd);
				phcd.writeStatistics(tv.getTime(), toAdd);
			}
		}
	}
}

class ValuedCounterFactory implements CounterFactory
{

	@Override
	public ValuedCounter get(String name)
	{
		if (name != null && name.startsWith(ValuedCounter.V_PREFIX))
		{
			return new ValuedCounter(name.substring(ValuedCounter.V_PREFIX.length()));
		}
		return null;
	}
}
